package com.cn.index;

import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.search.SearchHit;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;


public class ESIndexDemo {
  RestHighLevelClient client;

  @Before
  public void before() {
//    List<Node> nodes = Lists.newArrayList();
    RestClientBuilder builder = RestClient.builder(
            new HttpHost("10.211.55.3", 9200, "http"));
    client = new RestHighLevelClient(builder);
  }

  @Test
  public void test2() {
    try {
      XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
      builder.field("word", "正常的location，无nested");
      //nested 嵌套类型
//      builder.field("multirank", "[{\"cityid\":2,\"rank\":2}]");
      //geo_point geo类型
      builder.field("location", "31.101,121.101");
      builder.endObject();
      IndexRequest indexRequest = new IndexRequest("my_store").source(builder);
      IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
      System.out.println(indexResponse);
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

  @Test
  public void test3() {
    try {
      XContentBuilder builder = JsonXContent.contentBuilder().prettyPrint();
      String nestedExample = "{\"foo\": {\"bar\":\"baz\"}}";
      XContentParser parser = JsonXContent.jsonXContent
              .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, nestedExample);
      builder.startObject();
      builder.startArray("name");
      builder.copyCurrentStructure(parser);
      builder.endArray();
      builder.endObject();
      System.out.println(builder.getOutputStream());
    } catch (IOException e) {
      e.printStackTrace();
    }

  }


  private void println(SearchResponse search) {
    if (search != null) {
      for (SearchHit hit : search.getHits()) {
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        System.out.println("docid:" + hit.getId());
      }

    }
  }

}
